package com.dubbo.rpc.discovery.strategy;

import com.dubbo.rpc.common.LoadBalanceStrategyEnum;
import com.dubbo.rpc.domain.ProviderInfo;
import com.dubbo.rpc.domain.ServiceDiscoveryInfo;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 负载均衡 - 随机
 * @author liuxin
 */
@Component
public class RandomStrategy implements AbstractLoadBalanceStrategy {

    @Override
    public LoadBalanceStrategyEnum strategy() {
        return LoadBalanceStrategyEnum.RANDOM;
    }

    @Override
    public ProviderInfo select(ServiceDiscoveryInfo serviceDiscoveryInfo) {
        List<ProviderInfo> providerInfoList = serviceDiscoveryInfo.getProviderInfoList();
        // 结果区间：[ 0, list.size() - 1 ]
        return providerInfoList.get(RandomUtils.nextInt(0, providerInfoList.size()));
    }
}
